#pragma once
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Route.hpp"
using namespace ns_log;
#define MAX_BUFFER_SIZE 4096


class nocopy
{
public:
    nocopy(){}
    ~nocopy(){}
    nocopy(const nocopy&) = delete;
    const nocopy& operator=(const nocopy&) = delete;
};
using server_t = std::function<void(int sockfd, const std::string &info, InetAddr& addr)>;
class UdpServer : public nocopy
{
private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    server_t _route_call_back;
public:
    UdpServer(uint16_t port,const server_t& task) : _port(port), _isrunning(false),_route_call_back(task)
    {
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "---create socketfd failed !----\n");
            abort();
        }
        LOG(DEBUG, "---create sockfd succsee,sockfd = %d---\n", _sockfd);
        // bind
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = ::htons(_port); // 本地序列转网络序列
        // bind任意ip
        addr.sin_addr.s_addr = INADDR_ANY;//INADDR_ANY--表示bind任意地址"0.0.0.0"
        int res = ::bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (res < 0)
        {
            LOG(FATAL, "server bind error!\n");
            abort();
        }
        LOG(DEBUG, "server bind success!\n");
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buff[MAX_BUFFER_SIZE];
            // 接收信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buff[n] = 0;
                InetAddr addr(peer);
                std::cout<<addr.GetInetAddrStr()<<"#: "<<buff<<std::endl;
                //回调进行处理
               _route_call_back(_sockfd,buff,addr);
            }
            else 
            {
               LOG(ERROR,"recv error!\n");
            }
        }
    }
    void Close()
    {
        if(_sockfd > 0) ::close(_sockfd);
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~UdpServer()
    {
    }
};